#include "processimage.h"

#include <QVector>
#include <QRgb>

namespace qrcode{

ProcessImage::ProcessImage()
{

}

void ProcessImage::ToBinarization(QImage &image)
{
    //1.转换为灰度图
    ToGray(image);

    //2.二值化
    QSize size = image.size();
    QImage binaryImage(size, QImage::Format_RGB32);
    QRgb pixel;
    for(int i = 0; i < size.width(); i++) {
        for(int j = 0; j < size.height(); j++) {
            pixel = image.pixel(i, j);
            int rgb = qGreen(pixel);
            //然后按某一阀值进行二值化
            if (rgb > 128){
                rgb = 255;
            } else {
                rgb = 0;
            }
            pixel = qRgb(rgb, rgb, rgb);
            binaryImage.setPixel(i, j, pixel);
        }
    }

    binaryImage.save("/home/daowm/Workspace/QtProjects/build-qrcode-qt-unknown-Debug/image/binaryImage.png");

    image = binaryImage;
}

void ProcessImage::RemoveBlank(QImage &image)
{
    QSize size = image.size();

    QImage result(size.width()-8, size.height()-8, QImage::Format_RGB32);

    for(int i = 0; i < result.width(); i++){
        for(int j = 0; j < result.height(); j++){
            result.setPixelColor(i, j, image.pixelColor(i+4, j+4));
        }
    }

    image = result;
}


void ProcessImage::ToGray(QImage &image)
{
    QSize colourImgSize = image.size();
    int width = colourImgSize.rwidth();
    int height = colourImgSize.rheight();
    unsigned char *colourImgDataPtr = image.bits();
    QImage grayImg(colourImgSize, QImage::Format_Indexed8);
    unsigned char *grayImgDataPtr = grayImg.bits();

    //下边这个for循环是直接取用green绿色分量值 来作为gray索引值
    for(int i = 0; i < height; i++)
    {
       for(int j = 0; j < width; j++)
       {
           *grayImgDataPtr = *(colourImgDataPtr + 1);
           colourImgDataPtr += 4;
           grayImgDataPtr++;
       }
    }

    QVector<QRgb> grayColourTable;
    unsigned int rgb = 0;
    for(int i = 0; i < 256; i++)
    {
       grayColourTable.append(rgb);
       rgb += 0x00010101;
    }

    grayImg.setColorTable(grayColourTable);
    grayImg.save("/home/daowm/Workspace/QtProjects/build-qrcode-qt-unknown-Debug/image/grayImage.png");

    image = grayImg;
}

}
